Each problem consists of a function to implement and instructions on how to implement the function. The parts of the function that need to be implemented are marked with a # TODO comment. After implementing the function, run the cell to test it against the unit tests we've provided. For each problem, we provide one or more unit tests from our project_tests package. These unit tests won't tell you if your answer is correct, but will warn you of any major errors. Your code will be checked for the correct solution when you submit it to Udacity.
When you implement the functions, you'll only need to you use the packages you've used in the classroom, like Pandas and Numpy. These packages will be imported for you. We recommend you don't add any import statements, otherwise the grader might not be able to run your code.
The other packages that we're importing are helper, project_helper, and project_tests. These are custom packages built to help you solve the problems. The helper and project_helper module contains utility functions and graph functions. The project_tests contains the unit tests for all the problems.
import sys
!{sys.executable} -m pip install -r requirements.txt
import pandas as pd
import numpy as np
import helper
import project_helper
import project_tests
While using real data will give you hands on experience, it's doesn't cover all the topics we try to condense in one project. We'll solve this by creating new stocks. We've create a scenario where companies mining Terbium are making huge profits. All the companies in this sector of the market are made up. They represent a sector with large growth that will be used for demonstration latter in this project.
df_original = pd.read_csv('../../data/project_2/eod-quotemedia.csv', parse_dates=['date'], index_col=False)
# Add TB sector to the market
df = df_original
df = pd.concat([df] + project_helper.generate_tb_sector(df[df['ticker'] == 'AAPL']['date']), ignore_index=True)
close = df.reset_index().pivot(index='date', columns='ticker', values='adj_close')
high = df.reset_index().pivot(index='date', columns='ticker', values='adj_high')
low = df.reset_index().pivot(index='date', columns='ticker', values='adj_low')
print('Loaded Data')
To see what one of these 2-d matrices looks like, let's take a look at the closing prices matrix.
close
Let's see what a single stock looks like from the closing prices. For this example and future display examples in this project, we'll use Apple's stock (AAPL). If we tried to graph all the stocks, it would be too much information.
apple_ticker = 'AAPL'
project_helper.plot_stock(close[apple_ticker], '{} Stock'.format(apple_ticker))
In this project you will code and evaluate a "breakout" signal. It is important to understand where these steps fit in the alpha research workflow. The signal-to-noise ratio in trading signals is very low and, as such, it is very easy to fall into the trap of overfitting to noise. It is therefore inadvisable to jump right into signal coding. To help mitigate overfitting, it is best to start with a general observation and hypothesis; i.e., you should be able to answer the following question before you touch any data:
What feature of markets or investor behaviour would lead to a persistent anomaly that my signal will try to use?
Ideally the assumptions behind the hypothesis will be testable before you actually code and evaluate the signal itself. The workflow therefore is as follows:

In this project, we assume that the first three steps area done ("observe & research", "form hypothesis", "validate hypothesis"). The hypothesis you'll be using for this project is the following:
Using this hypothesis, let start coding..
You'll use the price highs and lows as an indicator for the breakout strategy. In this section, implement get_high_lows_lookback to get the maximum high price and minimum low price over a window of days. The variable lookback_days contains the number of days to look in the past. Make sure this doesn't include the current day.
def get_high_lows_lookback(high, low, lookback_days):
"""
Get the highs and lows in a lookback window.
Parameters
----------
high : DataFrame
High price for each ticker and date
low : DataFrame
Low price for each ticker and date
lookback_days : int
The number of days to look back
Returns
-------
lookback_high : DataFrame
Lookback high price for each ticker and date
lookback_low : DataFrame
Lookback low price for each ticker and date
"""
#TODO: Implement function
#
# NOTE: Wasn't sure what this was asking for until I read 'Juanma G' explanation.
# https://knowledge.udacity.com/questions/10954
#
# Juanma G Explanation:
# Index and columns are those from the original DataFrame. The project is asking to get for each date which
# is the maximum value for that ticker given a window (for the high) and the minimum value for the low.
# For example, imagine your high (the parameter) is somethin like this:
# -----------------| JOPR |OQA | ........
# 2008-03-25 | 3 | 6 | ........
# 2008-03-26 | 1 | 2 | ........
# 2008-03-27 | 7 | 9 | ........
# 2008-03-28 | 8 | 7 | ........
# 2008-03-29 | 3 | 5 | ........
# And you are using a window of size 2 excluding the current value. The output should be like this:
# -----------------| JOPR | OQA | ........
# 2008-03-25 | NaN | NaN | ........
# 2008-03-26 | NaN | NaN | ........
# 2008-03-27 | 3 | 6 | ........
# 2008-03-28 | 7 | 9 | ........
# 2008-03-29 | 8 | 9 | ........
#
# Why? Well, for the 'JOPR' column the first 2 values are NaN cause they do not have enough previous value
# information for the window to compute the maximum. For 2008-03-27 the window is [3, 1] so the maximum value is 3. For 2008-03-28 the window is [1, 7] so the maximum value is 7. Finally, for 2008-03-29 the window is [7,8 ] so the maximum value is 8.
# For the low parameter the operations are the same, but you need to find the minimum value inside the window.
#
#----------------------------------------------------------------
# My implementation
#
# What this is doing:
# -We have a pandas dataframe dedicated for just the high prices for each ticker and one for the low prices.
# -We do not include today, so we use .shift(1) to go back 1 day
# -We use .rolling() to provide rolling window calculations, we provide the number of lookback days
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html
# -Find the max and the min of the high and low respectively.
# -Return the resulting dataframes.
lookback_high = high.shift(1).rolling(lookback_days).max()
lookback_low = low.shift(1).rolling(lookback_days).min()
return lookback_high, lookback_low
project_tests.test_get_high_lows_lookback(get_high_lows_lookback)
Let's use your implementation of get_high_lows_lookback to get the highs and lows for the past 50 days and compare it to it their respective stock. Just like last time, we'll use Apple's stock as the example to look at.
lookback_days = 50
lookback_high, lookback_low = get_high_lows_lookback(high, low, lookback_days)
project_helper.plot_high_low(
close[apple_ticker],
lookback_high[apple_ticker],
lookback_low[apple_ticker],
'High and Low of {} Stock'.format(apple_ticker))
Using the generated indicator of highs and lows, create long and short signals using a breakout strategy. Implement get_long_short to generate the following signals:
| Signal | Condition |
|---|---|
| -1 | Low > Close Price |
| 1 | High < Close Price |
| 0 | Otherwise |
In this chart, Close Price is the close parameter. Low and High are the values generated from get_high_lows_lookback, the lookback_high and lookback_low parameters.
def get_long_short(close, lookback_high, lookback_low):
"""
Generate the signals long, short, and do nothing.
Parameters
----------
close : DataFrame
Close price for each ticker and date
lookback_high : DataFrame
Lookback high price for each ticker and date
lookback_low : DataFrame
Lookback low price for each ticker and date
Returns
-------
long_short : DataFrame
The long, short, and do nothing signals for each ticker and date
"""
#TODO: Implement function
# -Create a DataFrame for the return with the same size by copying the close DataFrame.
# -Make all values 0 by default.
long_short = close.copy()
long_short[:] = 0
# Create masks (booleans of True and False) for signal generation
mask_plus_one_signal = lookback_high < close
mask_minus_one_signal = lookback_low > close
# Change values accordingly for the return DataFrame based on masks
long_short[mask_plus_one_signal] = 1
long_short[mask_minus_one_signal] = -1
# Cast to int64
# NOTE: Return a copy when copy=True
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html
long_short = long_short.astype( np.int64,
copy=True )
return long_short
project_tests.test_get_long_short(get_long_short)
Let's compare the signals you generated against the close prices. This chart will show a lot of signals. Too many in fact. We'll talk about filtering the redundant signals in the next problem.
signal = get_long_short(close, lookback_high, lookback_low)
project_helper.plot_signal(
close[apple_ticker],
signal[apple_ticker],
'Long and Short of {} Stock'.format(apple_ticker))
That was a lot of repeated signals! If we're already shorting a stock, having an additional signal to short a stock isn't helpful for this strategy. This also applies to additional long signals when the last signal was long.
Implement filter_signals to filter out repeated long or short signals within the lookahead_days. If the previous signal was the same, change the signal to 0 (do nothing signal). For example, say you have a single stock time series that is
[1, 0, 1, 0, 1, 0, -1, -1]
Running filter_signals with a lookahead of 3 days should turn those signals into
[1, 0, 0, 0, 1, 0, -1, 0]
To help you implement the function, we have provided you with the clear_signals function. This will remove all signals within a window after the last signal. For example, say you're using a windows size of 3 with clear_signals. It would turn the Series of long signals
[0, 1, 0, 0, 1, 1, 0, 1, 0]
into
[0, 1, 0, 0, 0, 1, 0, 0, 0]
clear_signals only takes a Series of the same type of signals, where 1 is the signal and 0 is no signal. It can't take a mix of long and short signals. Using this function, implement filter_signals.
For implementing filter_signals, we don't reccommend you try to find a vectorized solution. Instead, you should use the iterrows over each column.
def clear_signals(signals, window_size):
"""
Clear out signals in a Series of just long or short signals.
Remove the number of signals down to 1 within the window size time period.
Parameters
----------
signals : Pandas Series
The long, short, or do nothing signals
window_size : int
The number of days to have a single signal
Returns
-------
signals : Pandas Series
Signals with the signals removed from the window size
"""
# Start with buffer of window size
# This handles the edge case of calculating past_signal in the beginning
clean_signals = [0]*window_size
for signal_i, current_signal in enumerate(signals):
# Check if there was a signal in the past window_size of days
has_past_signal = bool(sum(clean_signals[signal_i:signal_i+window_size]))
# Use the current signal if there's no past signal, else 0/False
clean_signals.append(not has_past_signal and current_signal)
# Remove buffer
clean_signals = clean_signals[window_size:]
# Return the signals as a Series of Ints
return pd.Series(np.array(clean_signals).astype(np.int), signals.index)
def filter_signals(signal, lookahead_days):
"""
Filter out signals in a DataFrame.
Parameters
----------
signal : DataFrame
The long, short, and do nothing signals for each ticker and date
lookahead_days : int
The number of days to look ahead
Returns
-------
filtered_signal : DataFrame
The filtered long, short, and do nothing signals for each ticker and date
"""
#TODO: Implement function
# Copy to the final result
filtered_signal = signal.copy()
# Zero-out by default
filtered_signal[:] = 0
# DEBUG
#
#print(signal)
# Because clear_signals only takes a Series of the same type of signals,
# where 1 is the signal and 0 is no signal. It can't take a mix of long and short signals,
# we are going to make two DataFrames, one for long signals and one for short signals.
#
# NOTE: clear_signals can take all 1 and 0 OR -1 and 0. It just can't take 1, -1, and 0.
df_long = signal.copy()
df_short = signal.copy()
# Make masks to know what to remove.
# For the long DataFrame, remove short signals
# For the short DataFrame, remove the long signals
mask_remove_short = df_long == -1
mask_remove_long = df_short == 1
# Remove unwanted signals by making it equal to zero.
df_long[mask_remove_short] = 0
df_short[mask_remove_long] = 0
# Copy the long and short DataFrames to versions that will be filtered
df_long_filtered = df_long.copy()
df_short_filtered = df_short.copy()
# DEBUG
#
#print(df_long)
#print(df_short)
# Cycle through the columns.
# NOTE: A column of a pandas DataFrame is a pandas Series
# NOTE: df_long and df_short will have the same columns since they were split from
# the same original source. This means we only have to iterate once for both
# DataFrames.
for column in df_long:
# DEBUG
#
#print(df_long[column])
# Filter the pandas Series using the custom function
df_long_filtered[column] = clear_signals( df_long[column],
lookahead_days )
#
# # NOTE: clear_signals can take all 1 and 0 OR -1 and 0. It just can't take 1, -1, and 0.
df_short_filtered[column] = clear_signals( df_short[column],
lookahead_days )
# Combine the final result
# NOTE: Adding the filtered long and short DataFrames work because the when we split them due to
# signal (-1, 0, 1), we know that it will be mutually exclusive. Meaning that if we know that
# if there is a 1 in the long DataFrame, there cannot be a -1 in the short DataFrame, it has to
# be zero. Basically, if a DataFrame as a value that is not 0 the other DataFrame MUST have a
# value of 0. So when you add the two DataFrames, the end results will not clash.
filtered_signal[column] = df_long_filtered[column] + df_short_filtered[column]
###########################
# NOTE: The suggestion was to use iterrows over each column. However iterrows iterate each row
# and returns a Series. Unless you flip the columns as index and index as columns for the original
# DataFrame, the row is not what you want to filter. You could possibly use iteritems as well,
# but I found the method I use works. I am not sure the speed comparison.
###########################
return filtered_signal
project_tests.test_filter_signals(filter_signals)
Let's view the same chart as before, but with the redundant signals removed.
signal_5 = filter_signals(signal, 5)
signal_10 = filter_signals(signal, 10)
signal_20 = filter_signals(signal, 20)
for signal_data, signal_days in [(signal_5, 5), (signal_10, 10), (signal_20, 20)]:
project_helper.plot_signal(
close[apple_ticker],
signal_data[apple_ticker],
'Long and Short of {} Stock with {} day signal window'.format(apple_ticker, signal_days))
With the trading signal done, we can start working on evaluating how many days to short or long the stocks. In this problem, implement get_lookahead_prices to get the close price days ahead in time. You can get the number of days from the variable lookahead_days. We'll use the lookahead prices to calculate future returns in another problem.
def get_lookahead_prices(close, lookahead_days):
"""
Get the lookahead prices for `lookahead_days` number of days.
Parameters
----------
close : DataFrame
Close price for each ticker and date
lookahead_days : int
The number of days to look ahead
Returns
-------
lookahead_prices : DataFrame
The lookahead prices for each ticker and date
"""
#TODO: Implement function
# NOTE: This was kind of weird because the problem asked to get future prices
# which we almost never do due to look-ahead bias. I wasn't sure if that was really
# what they were asking to do.
#
# Anyway, the .shift() method usually takes positive int to get previous values.
# I am assuming positive numbers go back and not negative numbers because you
# are more likely to look back in time instead of forward in time. To look ahead
# (into the future,) you have to use positive numbers.
lookahead_prices = close.shift(-lookahead_days)
return lookahead_prices
project_tests.test_get_lookahead_prices(get_lookahead_prices)
Using the get_lookahead_prices function, let's generate lookahead closing prices for 5, 10, and 20 days.
Let's also chart a subsection of a few months of the Apple stock instead of years. This will allow you to view the differences between the 5, 10, and 20 day lookaheads. Otherwise, they will mesh together when looking at a chart that is zoomed out.
lookahead_5 = get_lookahead_prices(close, 5)
lookahead_10 = get_lookahead_prices(close, 10)
lookahead_20 = get_lookahead_prices(close, 20)
project_helper.plot_lookahead_prices(
close[apple_ticker].iloc[150:250],
[
(lookahead_5[apple_ticker].iloc[150:250], 5),
(lookahead_10[apple_ticker].iloc[150:250], 10),
(lookahead_20[apple_ticker].iloc[150:250], 20)],
'5, 10, and 20 day Lookahead Prices for Slice of {} Stock'.format(apple_ticker))
Implement get_return_lookahead to generate the log price return between the closing price and the lookahead price.
def get_return_lookahead(close, lookahead_prices):
"""
Calculate the log returns from the lookahead days to the signal day.
Parameters
----------
close : DataFrame
Close price for each ticker and date
lookahead_prices : DataFrame
The lookahead prices for each ticker and date
Returns
-------
lookahead_returns : DataFrame
The lookahead log returns for each ticker and date
"""
#TODO: Implement function
lookahead_returns = np.log(lookahead_prices) - np.log(close)
return lookahead_returns
project_tests.test_get_return_lookahead(get_return_lookahead)
Using the same lookahead prices and same subsection of the Apple stock from the previous problem, we'll view the lookahead returns.
In order to view price returns on the same chart as the stock, a second y-axis will be added. When viewing this chart, the axis for the price of the stock will be on the left side, like previous charts. The axis for price returns will be located on the right side.
price_return_5 = get_return_lookahead(close, lookahead_5)
price_return_10 = get_return_lookahead(close, lookahead_10)
price_return_20 = get_return_lookahead(close, lookahead_20)
project_helper.plot_price_returns(
close[apple_ticker].iloc[150:250],
[
(price_return_5[apple_ticker].iloc[150:250], 5),
(price_return_10[apple_ticker].iloc[150:250], 10),
(price_return_20[apple_ticker].iloc[150:250], 20)],
'5, 10, and 20 day Lookahead Returns for Slice {} Stock'.format(apple_ticker))
Using the price returns generate the signal returns.
def get_signal_return(signal, lookahead_returns):
"""
Compute the signal returns.
Parameters
----------
signal : DataFrame
The long, short, and do nothing signals for each ticker and date
lookahead_returns : DataFrame
The lookahead log returns for each ticker and date
Returns
-------
signal_return : DataFrame
Signal returns for each ticker and date
"""
#TODO: Implement function
# Copy returns to final output to get the same size.
# Default all values to 0.
signal_return = lookahead_returns.copy()
signal_return[:] = 0
# DEBUG
#
#print(lookahead_returns.isnull().values)
# Leave nan (not a number) values intact
mask_nan = lookahead_returns.isnull().values
signal_return[mask_nan] = np.nan
# Get masks for long and short
mask_signals_long = signal == 1
mask_signals_short = signal == -1
# Use the values for long position if the mask said it is a long position.
# NOTE: for short position, negate it.
signal_return[mask_signals_long] = lookahead_returns[mask_signals_long]
signal_return[mask_signals_short] = -lookahead_returns[mask_signals_short]
return signal_return
project_tests.test_get_signal_return(get_signal_return)
Let's continue using the previous lookahead prices to view the signal returns. Just like before, the axis for the signal returns is on the right side of the chart.
title_string = '{} day LookaheadSignal Returns for {} Stock'
signal_return_5 = get_signal_return(signal_5, price_return_5)
signal_return_10 = get_signal_return(signal_10, price_return_10)
signal_return_20 = get_signal_return(signal_20, price_return_20)
project_helper.plot_signal_returns(
close[apple_ticker],
[
(signal_return_5[apple_ticker], signal_5[apple_ticker], 5),
(signal_return_10[apple_ticker], signal_10[apple_ticker], 10),
(signal_return_20[apple_ticker], signal_20[apple_ticker], 20)],
[title_string.format(5, apple_ticker), title_string.format(10, apple_ticker), title_string.format(20, apple_ticker)])
project_helper.plot_signal_histograms(
[signal_return_5, signal_return_10, signal_return_20],
'Signal Return',
('5 Days', '10 Days', '20 Days'))
#TODO: Put Answer In this Cell
All three histograms visually seem to be normally distributed and not skewed to one side. To test mathematically, we could see if the total area under the curve is equal to 1 (https://www.pqsystems.com/qualityadvisor/DataAnalysisTools/interpretation/histogram_compare_to_normal.php). However, there seems to be outliers in 10 and 20 day histograms on the right side.
You might have noticed the outliers in the 10 and 20 day histograms. To better visualize the outliers, let's compare the 5, 10, and 20 day signals returns to normal distributions with the same mean and deviation for each signal return distributions.
project_helper.plot_signal_to_normal_histograms(
[signal_return_5, signal_return_10, signal_return_20],
'Signal Return',
('5 Days', '10 Days', '20 Days'))
While you can see the outliers in the histogram, we need to find the stocks that are causing these outlying returns. We'll use the Kolmogorov-Smirnov Test or KS-Test. This test will be applied to teach ticker's signal returns where a long or short signal exits.
# Filter out returns that don't have a long or short signal.
long_short_signal_returns_5 = signal_return_5[signal_5 != 0].stack()
long_short_signal_returns_10 = signal_return_10[signal_10 != 0].stack()
long_short_signal_returns_20 = signal_return_20[signal_20 != 0].stack()
# Get just ticker and signal return
long_short_signal_returns_5 = long_short_signal_returns_5.reset_index().iloc[:, [1,2]]
long_short_signal_returns_5.columns = ['ticker', 'signal_return']
long_short_signal_returns_10 = long_short_signal_returns_10.reset_index().iloc[:, [1,2]]
long_short_signal_returns_10.columns = ['ticker', 'signal_return']
long_short_signal_returns_20 = long_short_signal_returns_20.reset_index().iloc[:, [1,2]]
long_short_signal_returns_20.columns = ['ticker', 'signal_return']
# View some of the data
long_short_signal_returns_5.head(10)
This gives you the data to use in the KS-Test.
Now it's time to implement the function calculate_kstest to use Kolmogorov-Smirnov test (KS test) between a normal distribution and each stock's signal returns. Run KS test on a normal distribution against each stock's signal returns. Use scipy.stats.kstest perform the KS test.
For this function, we don't reccommend you try to find a vectorized solution. Instead, you should iterate over the groupby function.
from scipy.stats import kstest
def calculate_kstest(long_short_signal_returns):
"""
Calculate the KS-Test against the signal returns with a long or short signal.
Parameters
----------
long_short_signal_returns : DataFrame
The signal returns which have a signal.
This DataFrame contains two columns, "ticker" and "signal_return"
Returns
-------
ks_values : Pandas Series
KS static for all the tickers
p_values : Pandas Series
P value for all the tickers
"""
#TODO: Implement function
# Create pandas series for return
ks_values = pd.Series()
p_values = pd.Series()
# Arguments for scipy.stats.kstest
# https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html#scipy-stats-kstest
#
# Distribution parameters, used if rvs or cdf are strings.
normal_args = ( np.mean(long_short_signal_returns),
np.std(long_short_signal_returns) )
grouped = long_short_signal_returns.groupby('ticker')
for name, group in grouped:
sample = group['signal_return'].values
# https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.kstest.html#scipy-stats-kstest
# https://docs.scipy.org/doc/scipy-0.14.0/reference/stats.html#module-scipy.stats
# https://stackoverflow.com/questions/17901112/using-scipys-stats-kstest-module-for-goodness-of-fit-testing
test_stat, p_value = kstest(sample, 'norm', normal_args)
# Put in pandas Series.
ks_values[name] = test_stat
p_values[name] = p_value
return ks_values, p_values
project_tests.test_calculate_kstest(calculate_kstest)
Using the signal returns we created above, let's calculate the ks and p values.
ks_values_5, p_values_5 = calculate_kstest(long_short_signal_returns_5)
ks_values_10, p_values_10 = calculate_kstest(long_short_signal_returns_10)
ks_values_20, p_values_20 = calculate_kstest(long_short_signal_returns_20)
print('ks_values_5')
print(ks_values_5.head(10))
print('p_values_5')
print(p_values_5.head(10))
With the ks and p values calculate, let's find which symbols are the outliers. Implement the find_outliers function to find the following outliers:
pvalue_threshold.ks_threshold.def find_outliers(ks_values, p_values, ks_threshold, pvalue_threshold=0.05):
"""
Find outlying symbols using KS values and P-values
Parameters
----------
ks_values : Pandas Series
KS static for all the tickers
p_values : Pandas Series
P value for all the tickers
ks_threshold : float
The threshold for the KS statistic
pvalue_threshold : float
The threshold for the p-value
Returns
-------
outliers : set of str
Symbols that are outliers
"""
#TODO: Implement function
# List of tickers that are outliers.
# Will convert into a set later.
list_outliers_p_values = []
list_outliers_ks_values = []
# DEBUG
#
#print(ks_values)
#print(p_values)
#print(ks_threshold)
#print(pvalue_threshold)
# Mask the creteria
mask_p_values = p_values < pvalue_threshold
mask_ks_values = ks_values > ks_threshold
# Get the index that meet the creteria
# NOTE: .index is a parameter that returns the corresponding index which is a type pandas index
# .values converts the pandas index to python list.
list_outliers_p_values = p_values[mask_p_values].index.values
#
# Same idea
list_outliers_ks_values = ks_values[mask_ks_values].index.values
# DEBUG
#
#print( p_values[mask_p_values].index.values )
# Convert list into sets and find intersection, meaning
# symbols that are outliers in both.
set_outliers_p_values = set(list_outliers_p_values)
set_outliers_ks_values = set(list_outliers_ks_values)
# Find intersection, meaning symbols that are outliers in both.
outliers = set_outliers_p_values.intersection(set_outliers_ks_values)
return outliers
project_tests.test_find_outliers(find_outliers)
Using the find_outliers function you implemented, let's see what we found.
ks_threshold = 0.8
outliers_5 = find_outliers(ks_values_5, p_values_5, ks_threshold)
outliers_10 = find_outliers(ks_values_10, p_values_10, ks_threshold)
outliers_20 = find_outliers(ks_values_20, p_values_20, ks_threshold)
outlier_tickers = outliers_5.union(outliers_10).union(outliers_20)
print('{} Outliers Found:\n{}'.format(len(outlier_tickers), ', '.join(list(outlier_tickers))))
Let's compare the 5, 10, and 20 day signals returns without outliers to normal distributions. Also, let's see how the P-Value has changed with the outliers removed.
good_tickers = list(set(close.columns) - outlier_tickers)
project_helper.plot_signal_to_normal_histograms(
[signal_return_5[good_tickers], signal_return_10[good_tickers], signal_return_20[good_tickers]],
'Signal Return Without Outliers',
('5 Days', '10 Days', '20 Days'))
That's more like it! The returns are closer to a normal distribution. You have finished the research phase of a Breakout Strategy. You can now submit your project.
Now that you're done with the project, it's time to submit it. Click the submit button in the bottom right. One of our reviewers will give you feedback on your project with a pass or not passed grade. You can continue to the next section while you wait for feedback.